package com.utils;

import org.apache.commons.lang3.CharEncoding;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;

import javax.net.ssl.*;
import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;

/**
 * 通用http发送方法
 * 
 * @author ruoyi
 */
public class HttpUtils
{

    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param)
    {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try
        {
            String urlNameString = url + "?" + param;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e.getMessage());
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e.getMessage());
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e.getMessage());
        }
        finally
        {
            try
            {
                if (in != null)
                {
                    in.close();
                }
            }
            catch (Exception ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex.getMessage());
            }
        }
        return result.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param)
    {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            String urlNameString = url + "?" + param;
            log.info("sendPost - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e.getMessage());
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e.getMessage());
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e.getMessage());
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex.getMessage());
            }
        }
        return result.toString();
    }

    @SuppressWarnings("deprecation")
    public static String sendSSLPost(String url, String param)
    {
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
        try
        {
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            DataInputStream indata = new DataInputStream(is);
            String ret = "";
            while (ret != null)
            {
                ret = indata.readLine();
                if (ret != null && !ret.trim().equals(""))
                {
                    result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            log.info("recv - {}", result);
            conn.disconnect();
            indata.close();
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e.getMessage());
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e.getMessage());
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e.getMessage());
        }
        return result.toString();
    }


    private static class TrustAnyTrustManager implements X509TrustManager
    {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
        {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
        {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers()
        {
            return new X509Certificate[] {};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {
            return true;
        }
    }

    public static String post(String url, String jsonData, int socketTimeout, int connectTimeout) throws Exception {
        log.info("requestPost, url = {}, jsonData = {}", url, jsonData);
        String jsonStr = "";
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();

        CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(defaultRequestConfig)
                .build();
        HttpPost httppost = new HttpPost(url);
        //httppost.addHeader("x-forwarded-for","183.128.136.165");
        httppost.setEntity(new StringEntity(jsonData, CharEncoding.UTF_8));
        httppost.setHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        try {
            CloseableHttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                log.error("requestPost失败,statusCode = {}, 请求参数 = {}", statusCode, jsonData);
                return null;
            }
            HttpEntity entity = response.getEntity();
            jsonStr = EntityUtils.toString(entity, CharEncoding.UTF_8);
        } finally {
            httppost.releaseConnection();
        }
        log.info("requestPost, response = {}", jsonStr);
        return jsonStr;
    }

    public static String post(String url, String jsonData, int socketTimeout, int connectTimeout,String sign) throws Exception {
        log.info("requestPost, url = {}, jsonData = {}", url, jsonData);
        String jsonStr = "";
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();

        CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(defaultRequestConfig)
                .build();
        String urlNameString = url + "?" + jsonData;
        HttpPost httppost = new HttpPost(urlNameString);

        //httppost.setEntity(new StringEntity(jsonData, CharEncoding.UTF_8));
        httppost.setHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        httppost.setHeader("SIGN",sign);
        try {
            CloseableHttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                log.error("requestPost失败,statusCode = {}, 请求参数 = {}", statusCode, jsonData);
                return null;
            }
            HttpEntity entity = response.getEntity();
            jsonStr = EntityUtils.toString(entity, CharEncoding.UTF_8);
        } finally {
            httppost.releaseConnection();
        }
        log.info("requestPost, response = {}", jsonStr);
        return jsonStr;
    }

    public static String postForIn(String url, String jsonData, int socketTimeout, int connectTimeout,String token) throws Exception {
        log.info("requestPost, url = {}, jsonData = {}", url, jsonData);
        String jsonStr = "";
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();

        CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(defaultRequestConfig)
                .build();
        HttpPost httppost = new HttpPost(url);

        httppost.setEntity(new StringEntity(jsonData, CharEncoding.UTF_8));
        httppost.setHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        httppost.setHeader("access_token",token);
        httppost.addHeader("x-forwarded-for","183.128.136.165");
        try {
            CloseableHttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                log.error("requestPost失败,statusCode = {}, 请求参数 = {}", statusCode, jsonData);
                HttpEntity entity = response.getEntity();
                jsonStr = EntityUtils.toString(entity, CharEncoding.UTF_8);
                return jsonStr;
            }
            HttpEntity entity = response.getEntity();
            jsonStr = EntityUtils.toString(entity, CharEncoding.UTF_8);
        } finally {
            httppost.releaseConnection();
        }
        log.info("requestPost, response = {}", jsonStr);
        return jsonStr;
    }

    public static String postWayBill(String url, String jsonData, int socketTimeout, int connectTimeout) throws Exception {
        log.info("requestPost, url = {}, jsonData = {}", url, jsonData);
        String jsonStr = "";
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();

        CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(defaultRequestConfig)
                .build();
        HttpPost httppost = new HttpPost(url);
        //httppost.addHeader("x-forwarded-for","183.128.136.165");
        httppost.setEntity(new StringEntity(jsonData, CharEncoding.UTF_8));
        httppost.setHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        httppost.setHeader("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1c2VyIjoie1wiY29tcGFueUlkXCI6MjAxODM3LFwic2VsbGVySWRcIjoyMDE4MzcsXCJzdXBwbGllcklkXCI6MjAxODM3LFwidXNlcm5hbWVcIjpcInpoYW9lbmxvbmdAeXZvZ3VlLmNvbVwifSIsInBhcmFtcyI6Int9IiwicGVybSI6InVzZXIiLCJpc3MiOiJ2b3lhZ2VvbmUiLCJzdWIiOiJqd3QiLCJpYXQiOjE2MjMxMTAxNzMsImV4cCI6MTYyNTcwMjE3M30.i1mVOHCtPwUvofWZ14qwfwLk1XZuRyaGqWA3Rmn1gja3oxCpkIcpcmNWnqZe_KYVEg4sXndGj5Rr450x3aOy0g_Wh6yUgS34uoCu4jTDRZimmBptruQas2RWnWa67HFq7rrK5W8MXUfK5MXyJVlj82F2e91CUHy9_N4NKOorMleB67x5mzIr_sRK0icVQlLxE0OeRJdAjnHuwqeFKg324SJb930eaSy9yOLBj5NXQZna1JhNf9Gfk0F95sDIEnEPE6oKgHczk9OOkf5MMeAbB3OYh1EDzXl3m3UH4-hEgfRB_y90niusuXXOkIuAgkYC1QgXTZtPXGamE63mojc6rA");
        try {
            CloseableHttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                log.error("requestPost失败,statusCode = {}, 请求参数 = {}", statusCode, jsonData);
                return null;
            }
            HttpEntity entity = response.getEntity();
            jsonStr = EntityUtils.toString(entity, CharEncoding.UTF_8);
        } finally {
            httppost.releaseConnection();
        }
        log.info("requestPost, response = {}", jsonStr);
        return jsonStr;
    }
}